package org.openkoala.security.controller;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.filter.DelegatingFilterProxy;

public class DrgDelegatingFilterProxy extends DelegatingFilterProxy {
	private volatile Filter delegate;
	private final Object delegateMonitor = new Object();
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		HttpServletResponse responseh = (HttpServletResponse) response;
		responseh.setHeader("Access-Control-Allow-Origin", "*");  
		responseh.setHeader("Access-Control-Allow-Headers", "X-Pagination-Current-Page,Content-Type,Content-Length, Authorization, Accept,X-Requested-With");  
		responseh.setHeader("Access-Control-Expose-Headers", "X-Pagination-Current-Page,Content-Type");
		responseh.setHeader("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS,HEAD");  
		responseh.setHeader("X-Powered-By","Jetty");  
		// Lazily initialize the delegate if necessary.
		Filter delegateToUse = this.delegate;
		if (delegateToUse == null) {
			synchronized (this.delegateMonitor) {
				if (this.delegate == null) {
					WebApplicationContext wac = findWebApplicationContext();
					if (wac == null) {
						throw new IllegalStateException("No WebApplicationContext found: no ContextLoaderListener registered?");
					}
					this.delegate = initDelegate(wac);
				}
				delegateToUse = this.delegate;
			}
		}
		//filterChain.doFilter(request, responseh);
		// Let the delegate perform the actual doFilter operation.
		invokeDelegate(delegateToUse, request, responseh, filterChain);
	}
}
